package leetcode.lt100;

class Solution_79 {

//    board =
//            [
//            ['A','B','C','E'],
//            ['S','F','C','S'],
//            ['A','D','E','E']
//            ]
// (x,y) (0,1) = 'B'

    public static void main(String[] args) {

    }

    int x;
    int y;
    boolean[][] visited = new boolean[x][y];

    public boolean exist(char[][] board, String word) {
        x = board.length;
        y = board[0].length;
        for (int i = 0; i < x; i++) {
            for (int j = 0; j < y; j++) {
                if (dfs(board, i, j, word, 0)) {
                    return true;
                }
            }
        }
        return false;
    }

    private boolean dfs(char[][] board, int i, int j, String word, int index) {
        if (word.length() == index) {
            return true;
        }
        if (crossBoundary(i, j)) {
            return false;
        }
        if (visited[i][j]) {
            return false;
        }
        if (word.charAt(index) != board[i][j]) {
            return false;
        }
        visited[i][j] = true;
        if (dfs(board, i + 1, j, word, index + 1)) {
            return true;
        }
        if (dfs(board, i - 1, j, word, index + 1)) {
            return true;
        }
        if (dfs(board, i, j + 1, word, index + 1)) {
            return true;
        }
        if (dfs(board, i, j - 1, word, index + 1)) {
            return true;
        }
        visited[i][j] = false;
        return false;
    }

    private boolean crossBoundary(int i, int j) {
        if (i < 0 || i >= x) {
            return true;
        }
        if (j < 0 || j >= y) {
            return true;
        }
        return false;
    }

}